package leetcode_acm.string;

import java.util.*;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年03月21日 19:47
 */
public class GroupAnagrams {
    public static final String SEP = ",";
    private Map<String,List<String>> map = new HashMap<>();
    public List<List<String>> groupAnagrams(String[] strs) {
        //1. 预处理当前的字符串数组
        for (int i = 0; i < strs.length; i++) {
            int length = strs[i].length();
            int[] memo = new int[26];
            for (int j = 0; j < length; j++) {
                memo[strs[i].charAt(j) - 'a']++;
            }
            StringBuilder sb = new StringBuilder();
            //然后将当前的String组成一个key
            for (int k = 0; k < 26; k++) {
                if(memo[k] != 0){
                    sb.append(k+'a').append(memo[k]).append(SEP);
                }
            }
            List<String> strings = map.get(sb.toString());
            if(strings == null){
                map.put(sb.toString(),new LinkedList<>());
            }
            strings.add(strs[i]);
        }
        //2. 预处理完毕后,将相同的key添加到一起
        List<List<String>> list = new LinkedList<>();
        for (Map.Entry<String, List<String>> stringListEntry : map.entrySet()) {
            list.add(stringListEntry.getValue());
        }
        return list;
    }
}
